package com.myapp.web.action.util;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.util.ServletContextAware;
import org.springframework.web.context.support.ServletContextResourceLoader;
import com.myapp.model.entity.product.Picture;
import com.myapp.service.product.ProductBo;
import com.myapp.util.Constants;
import com.myapp.util.xwork.PropertiesAware;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport implements PropertiesAware,ServletContextAware,
      ServletResponseAware,ServletRequestAware,SessionAware{	
	
	private static final long serialVersionUID = 3503328515741220539L;
	private ServletContext servletContext;
	private HttpServletRequest request;
	// 封装上传文件的属性
	private File upload;
	// 封装上传文件名称属性
	private String uploadFileName;
	// 封装上传文件类型属性
	private String uploadContentType;	
	// 保存文件名称属性
	private String targetFileName;
	
	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
	
	private Properties props;
	private HttpServletResponse response;
	private Map<String,Object> sessionMap;
	private ProductBo prodBo;
	private Random seed = new Random();
	
	public void setProdBo(ProductBo prodBo) {
		this.prodBo = prodBo;
	}

	public String upload() throws Exception{
		File targetFile = null;
		String dir = props.getProperty(Constants.APP_UPLOAD_DIR);
		String localFile = props.getProperty(Constants.USE_LOCAL_FILE);
		if(!StringUtils.isEmpty(localFile) && Integer.valueOf(localFile)!= 0){
			targetFile = new File(dir,uploadFileName);
		}else{
			ServletContextResourceLoader resourceLoader = new ServletContextResourceLoader(servletContext);
			targetFile = new File(resourceLoader.getResource(dir).getFile(),uploadFileName);
		}		
		
		try{			
			if(targetFile.exists()){
				targetFile.delete();
			}
			FileUtils.copyFile(upload, targetFile);
			String url = props.getProperty(Constants.APP_UPLOAD_URL) + uploadFileName;
			response.setCharacterEncoding("UTF-8");
			//response.setContentType("text/json; charset=utf-8");
			response.setContentType("text/plain");
			//response.addHeader("Content-Type","text/plain");
			System.out.println("upload path*********"+ this.request.getServletPath());
			Picture pic = new Picture();
			pic.setPath(url);
			pic.setPicName(uploadFileName);
			pic.setProdId(getProdId());
			prodBo.addPicture(pic);
			JSONObject jsonObj = new JSONObject();
			jsonObj.put("url", url);
			System.out.println(jsonObj.toString());
			response.getWriter().write(jsonObj.toString());			
			System.out.println(url);
			System.out.println(targetFile.getPath());	
		}catch(IOException e)
		{
			e.printStackTrace();
			throw e;
		}
		return NONE;
	}

	private int getProdId(){		   
		Integer prodId = (Integer)sessionMap.get(Constants.PROD_ID_SESSION_KEY);
		if(prodId != null){
			return prodId.intValue();
		}
		prodId = Math.abs(seed.nextInt());
		ActionContext.getContext().getSession().put(Constants.PROD_ID_SESSION_KEY, prodId);
		sessionMap.put(Constants.PROD_ID_SESSION_KEY, prodId);
		return prodId.intValue();
	}	
	
	@Override
	public void setProperties(Properties p) {
		props = p;
	}
	
	@Override
	public void setServletResponse(HttpServletResponse resp) {
		response = resp;
	}
		
	@Override
	public void setSession(Map<String, Object> session) {
		sessionMap = session;
		if(!session.isEmpty()){
			Set<Entry<String,Object>> set = session.entrySet();
			Iterator<Entry<String,Object>> it = set.iterator();
			while(it.hasNext()){
				Entry<String,Object> e = it.next();
				System.out.println("key: " + e.getKey() + "value : " + e.getValue().toString());
			}
		}
	}

	@Override
	public void setServletContext(ServletContext context) {
		servletContext = context;		
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;		
	}
}
